'use strict';
//
exports.main = async (event, context) => {
	//event为客户端上传的参数
	console.log('event : ', event)
	//获取数据库的对象
	const db = uniCloud.database();
	//获取表的对象
	const tb = db.collection("user");
	//一个给对象设置值的对象
	const dbCmd = db.command;
	//根据类型进行操作
	switch (event.type) {
		//登录
		case 'login': {
			let res = {
				status: 201,
				data: '',
				msg: '用户名或者密码错误！'
			};
			let { userInfo } = event;
			//查询
			const data = await tb.where({
				username: userInfo.username,
				password: userInfo.password
			}).get()
			//查询不到数据
			if (data.affectedDocs == 0) return res;
			//查到该用户并返回
			res = {
				status: 200,
				data: data,
				msg: '登录成功！'
			}
			return res;
		};
		//注册
		case "regist": {
			//提取参数
			let {
				type
			} = event;
			let res = await tb.add({
				type
			});
			return res;
		};
		//修改用户求职状态
		case "changeUserJobState": {
			let {
				_id,
				job_state
			} = event;
			//修改
			let upObj = await tb.doc(_id).
			update({
				"job_state": dbCmd.set(job_state)
			})
			//查询该对象并返回前台
			let user = await tb.where({
				_id: _id
			}).get()
			return {
				status: 200,
				upObj: upObj,
				user: user
			}

		};
		//修改用户信息
		case "updateUser": {
			let {
				form,
				_id
			} = event;
			//修改
			let updateResult = await tb.doc(_id).update({
				"head_image": dbCmd.set(form.head_image),
				"real_name": dbCmd.set(form.real_name),
				"password": dbCmd.set(form.password)
			})
			//第二次查询 根据id查找对象，将修改后的对象返回
			let user = await tb.where({
				_id: _id
			}).get()
			return {
				status: 200,
				updateResult: updateResult,
				user: user
			}
		};

		//根据用户id查找该用户
		case "selectUserById": {
			let {
				_id
			} = event;
			//查找
			let user = await tb.where({
				_id: _id
			}).get()
			return {
				status: 200,
				user: user
			}
		}
	};
};
